import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    redirect: "/user/login",
  },
  {
    path: "/user/login",
    name: "UserLogin",
    component: () =>
      import(/* webpackChunkName: "UserLogin" */ "@/views/user/login.vue"),
  },
  {
    path: "/user/registry",
    name: "UserRegistry",
    component: () =>
      import(/* webpackChunkName: "UserRegistry" */ "@/views/user/regis.vue"),
  },
  {
    path: "/home",
    name: "home",
    component: () =>
      import(/* webpackChunkName: "home" */ "@/views/home/index.vue"),
  },
  {
    path: "/fen",
    name: "fen",
    component: () => import(/* webpackChunkName: "fen" */ "@/views/Fen.vue"),
  },
  {
    path: "/shop",
    name: "shop",
    component: () => import(/* webpackChunkName: "shop" */ "@/views/Shop.vue"),
  },
  {
    path: "/my",
    name: "my",
    component: () => import(/* webpackChunkName: "my" */ "@/views/My.vue"),
  },
  {
    path: "/404",
    name: "NotFound",
    component: () =>
      import(/* webpackChunkName: "NotFound" */ "@/views/common/404.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

export default router;

//路由守卫
router.beforeEach((to, form, next: any) => {
  if (to.meta !== undefined && to.meta.requireAuth) {
    if (localStorage.getItem("token")) {
      next();
    } else {
      next({
        name: "login",
        query: {
          redirect: encodeURIComponent(to.path),
        },
        replace: true,
      });
      return false;
    }
  } else {
    next();
  }
});
